import threading
import time

from  apilib.component import compManager , TComp
class TPluginEquTsDress( TComp):
    def __init__(self):
        super().__init__()
        self.resultId =0
        self.resultInfo ={}
        self.actions={}
        self.dbLock = threading.Lock()
        self.handlers={
            "setRssult": self.setRssult
        }
    def getDB(self):
        res =None
        try:
            dbCode = self.compSettings['dbCode']
            res = self.manager.components[dbCode]
        except Exception as er:
            self.manager.log(er)
        return res
    def setRssult(self, resutId):
        res ={}
        try:
            db = self.getDB()
            self.resultId = resutId
            resp =  db.execProc("getResultDetail",{"resultId": self.resultId})
            self.resultInfo= resp['datasetList'][0][0]
            self.actions ={}
            for action in resp['datasetList'][1]:
                action["scores"]={}
                actionId = action['actionId']
                self.actions[actionId]= action
            for score in resp['datasetList'][2]:
                actionId = score['actionId']
                referCode = score['referCode']
                self.actions[actionId]['scores'][referCode] = score
            res ={
                "resultInfo": self.resultInfo,
                "actions": self.actions
            }
        except Exception as er:
            self.manager.log(er)
        return res
    def setScore(self , actionId , refereeCode ,  score):
        res ={
            "status":0
        }
        try:
            scoreInfo = self.actions[actionId]['scores'][refereeCode]
            scoreInfo['score']=score
            scoreInfo['tm'] = time.time()
            self.getDB().executeAsync (actionCode="updateRow" , table="T_Score", fieldValues={"scoreId":scoreInfo['tm']} , keyValues={"score": score})
            res={
                 "status":1
            }
        except Exception as er:
            self.manager.log(er)
        return res

_settings = {
    "dbCode":"equTsV2_db",
}
compManager.registComponentType('TPluginEquTsDress' , TPluginEquTsDress , _settings)
